//
//  HNFamousDoctorController.m
//  JHFBaseProject
//
//  Created by 朱传正 on 2016/12/29.
//  Copyright © 2016年 好牛. All rights reserved.
//

#import "HNFamousDoctorController.h"
#import "HNDoctorDetailViewController.h"

@interface HNFamousDoctorController ()

@property (nonatomic,assign)CGFloat contentHeight;

@property (nonatomic,strong)NSMutableArray *docterListSource;

@property (nonatomic,assign)NSInteger docterListCount;

@property (nonatomic,assign) NSUInteger cur;//当前
@property (nonatomic,assign) CGFloat currentTag;

@property (nonatomic,strong) UIView *shoppingView;

@end

@implementation HNFamousDoctorController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"名医";
    [self drawView];
    [self initData];
}

-(void)drawView{
    

    _contentHeight = 0;
    
    self.view.backgroundColor = RGBJ(241);
    
    _doctorListScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height-70)];
    _doctorListScrollView.bounces = YES;
    
    [self.view addSubview:_doctorListScrollView];
    
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0.5)];
    lineLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:lineLabel];
    
    MJRefreshGifHeader *header = [[MJRefreshGifHeader alloc]init];
    
    [header setRefreshingBlock:^(void){
        [self getDoctorMessage:1];
    }];
    self.doctorListScrollView.mj_header = header;
    
    //下拉刷新
    _doctorListScrollView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^(void){
        _cur ++;
        [self getDoctorMessage:_cur];
    }];

    //设置医生列表
    _doctorListScrollView.backgroundColor = RGB(236, 240, 241);
    
    _shoppingView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0)];
    [_doctorListScrollView addSubview:_shoppingView];
    
    
    [self setDoctorList];

    
//    _doctorListScrollView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreDoctorMessage)];
    
}


#pragma mark - 设置列表
-(void)setDoctorList{
    CGFloat bl = 6;//border边距
    CGFloat gl = 4;//gap间隙
    
    NSInteger num = self.docterListSource.count;
    
    NSLog(@"------------self.docterListSource = %@",self.docterListSource);

    //当商品列表为空时
    
    for (NSInteger i = 0; i < self.docterListSource.count; i++) {
        
        NSDictionary *goodsDataDic  = self.docterListSource[i];
        UIView *itemView = [[UIView alloc]initWithFrame:CGRectMake((kScreen_Width/2 - bl/2) * !(i%2 == 0) + bl, _contentHeight, kScreen_Width/2, 0)];
        [self.shoppingView addSubview:itemView];
        //商品图
        UIImageView *goodsImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, gl * 2, kScreen_Width/2 - bl*3/2, kScreen_Width/2 - bl*3/2)];
        
        NSString *goodsImageStr = [NSString stringWithFormat:@"%@%@",url_Base,[goodsDataDic objectForKey:@"photo"]];
        [goodsImageView sd_setImageWithURL:[NSURL URLWithString:goodsImageStr] placeholderImage:[UIImage imageNamed:@"D99GN4P63Q4F@2x.png"]];
        
        goodsImageView.layer.masksToBounds = YES;
        
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:goodsImageView.bounds  byRoundingCorners: UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii: (CGSize){5.0f, 5.0f}].CGPath;
        goodsImageView.layer.mask = maskLayer;
        
        [itemView addSubview:goodsImageView];
        
        //商品名
        UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, goodsImageView.frame.origin.y + goodsImageView.frame.size.height, goodsImageView.frame.size.width, 18 + gl)];
        nameLabel.numberOfLines = 1;
        nameLabel.backgroundColor = [UIColor whiteColor];
        nameLabel.font = [UIFont systemFontOfSize:15];
        nameLabel.textColor = RGBJ(165);
        NSString *realName = [NSString stringWithFormat:@"%@",[goodsDataDic objectForKey:@"realName"]];
        NSString *nickname = [NSString stringWithFormat:@"%@",[goodsDataDic objectForKey:@"nickname"]];
        NSString *username = [NSString stringWithFormat:@"%@",[goodsDataDic objectForKey:@"username"]];
        if ([AppConfig isNULL:nickname]) {
            if ([AppConfig isNULL:realName]){
                nameLabel.text = username;
            }else{
                nameLabel.text = realName;
            }
        }else {
            nameLabel.text = nickname;
        }
        [itemView addSubview:nameLabel];
        //商品描述
        UILabel *detailLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, nameLabel.frame.origin.y + nameLabel.frame.size.height, goodsImageView.frame.size.width, 15 + gl)];
        detailLabel.backgroundColor = [UIColor whiteColor];
        detailLabel.numberOfLines = 1;
        detailLabel.font = [UIFont systemFontOfSize:11];
        detailLabel.textColor = RGB(112, 112, 112);
        
        detailLabel.text = [NSString stringWithFormat:@" %@",[goodsDataDic objectForKey:@"flag1"]];
        [itemView addSubview:detailLabel];
        
        
        UIView *gapView = [[UIView alloc]initWithFrame:CGRectMake(0, detailLabel.frame.origin.y + detailLabel.frame.size.height, goodsImageView.frame.size.width, 10)];
        
        gapView.layer.masksToBounds = YES;
        
        CAShapeLayer *gapViewLayer = [CAShapeLayer layer];
        gapViewLayer.path = [UIBezierPath bezierPathWithRoundedRect:detailLabel.bounds  byRoundingCorners: UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii: (CGSize){5.0f, 5.0f}].CGPath;
        detailLabel.layer.mask = gapViewLayer;
        
        [itemView addSubview:detailLabel];
        
        //添加点击按钮
        UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [clickBtn setTitle:@"" forState:UIControlStateNormal];
        [clickBtn setBackgroundColor:RGBA(255, 255, 255, 0)];
        [clickBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        clickBtn.tag = i + 10000;
        clickBtn.frame = goodsImageView.frame;
        [clickBtn addTarget:self action:@selector(enterDoctorDetail:) forControlEvents:UIControlEventTouchUpInside];
        [itemView addSubview:clickBtn];
       
        //设置列表高度
        CGRect itemViewFrame = itemView.frame;
        itemViewFrame.size.height = goodsImageView.frame.size.height + detailLabel.frame.size.height + nameLabel.frame.size.height + gapView.frame.size.height ;
        itemView.frame = itemViewFrame;
        if (i%2 == 1 || (i + 1 == num && num%2 == 1)) {
            //设置列表高度
            _contentHeight = _contentHeight + itemView.frame.size.height;
            //最后一行加载后再改变scrollView高度
            if(i + 1 == num){
            _doctorListScrollView.contentSize = CGSizeMake(kScreen_Width, _contentHeight);
            }
            //设置商品高度
            CGRect shoppingViewFrame = self.shoppingView.frame;
            shoppingViewFrame.size.height = shoppingViewFrame.size.height + itemView.frame.size.height;
            self.shoppingView.frame = shoppingViewFrame;
        }
    }
    
    
    self.docterListCount = self.docterListSource.count;
    
}

#pragma -mark 进入医生详情页
-(void)enterDoctorDetail:(UIButton *)btn{
    NSInteger tag = btn.tag - 10000;
    NSDictionary *dic = _docterListSource[tag];
    NSString *userId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"userId"]];
    
    HNDoctorDetailViewController *doctorDetailVC = [[HNDoctorDetailViewController alloc]init];
    doctorDetailVC.title = @"医生详情";
    doctorDetailVC.userId = userId;
    [self.navigationController pushViewController:doctorDetailVC animated:YES];
}


-(void)initData{
    self.docterListSource = [[NSMutableArray alloc]init];
    
    [self getDoctorMessage:1];
}


#pragma mark - 获取消息
-(void)getDoctorMessage:(NSInteger)cur{

    _docterListSource = [[NSMutableArray alloc]init];
    _docterListCount = 0;
    
  
    
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"cur",@"1",@"isDoctor",nil];
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_doctor_list parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取医生列表失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSArray * obj = [NSArray arrayWithArray:[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",obj);
            
            for (int i = 0; i < obj.count; i ++) {
                NSLog(@"%@",obj[i]);
                [self.docterListSource addObject:obj[i]];
            }
            
            NSLog(@"===self.docterListSource = %@",self.docterListSource);
            
    
            
            [_shoppingView removeFromSuperview];
            
            
               _contentHeight = 0;
            _shoppingView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height-50)];
            [self.doctorListScrollView addSubview:_shoppingView];
            
         
            
            [self setDoctorList];
            
            
            [self.doctorListScrollView.mj_header endRefreshing];
             [self.doctorListScrollView.mj_footer endRefreshing];
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
            [self.doctorListScrollView.mj_header endRefreshing];
            [self.doctorListScrollView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取医生列表失败"];
        [self.doctorListScrollView.mj_header endRefreshing];
        [self.doctorListScrollView.mj_footer endRefreshing];
    }];
    
    
}




@end
